import pymysql
from PythonUtils.mysql.mysqlUI.UIDataBaseView import *
class MysqlUtilsWithUI():
    def __init__(self, statement=True):
        self.conn = None
        self.uiDataBaseView = UIDataBaseView()
        self.uiDataBaseView.submitCallback = self.connect
        self.connect()
        if statement: self.statement()

    def connect(self):
        if not os.path.isfile(os.path.dirname(os.path.realpath(__file__)) + '/mysqlUI/database.ini'):
            with open(os.path.dirname(os.path.realpath(__file__)) + '/mysqlUI/database.ini', 'w+') as fp:
                fp.write("[mysql]\nhost = \ndb = \nuser = \npassword = \nport = \ncharset = \nprefix = \ndatetime_format = \n")
        conf = configparser.ConfigParser()
        conf.read(os.path.dirname(os.path.realpath(__file__)) + '/mysqlUI/database.ini', encoding="utf-8")
        mysql_items = {}
        for item in conf.items("mysql"):
            mysql_items[item[0]] = item[1]
        try:
            self.conn = pymysql.connect(host=mysql_items['host'],
                                    user=mysql_items['user'],
                                    password=mysql_items['password'],
                                    port=int(mysql_items['port']),
                                    db=mysql_items['db'],
                                    charset=mysql_items['charset'])
        except:
            print("数据库连接初始化失败，请检查配置！")
            self.uiDataBaseView.show()

    def createtable(self, sql):
        if not self.conn: return
        if sql:
            cursor = self.conn.cursor(buffered=True)
            cursor.execute(sql)
            cursor.close()
            return 'success'
        else:
            return 'error'

    def insert(self, sql):
        if not self.conn: return
        if sql:
            cursor = self.conn.cursor()
            cursor.execute(sql)
            cursor.close()
            return 'success'
        else:
            return 'error'

    def delete(self, id, table='', sql=''):
        if not self.conn: return
        if sql:
            sql = sql
        elif table:
            sql = "delete from %s where id=%d" % (table, id)
        else:
            return 'error'
        cursor = self.conn.cursor()
        cursor.execute(sql)
        self.conn.commit()
        cursor.close()
        return 'success'

    def select(self, table='', sql=''):
        if not self.conn: return
        if sql:
            sql = sql
        elif table:
            sql = "select * from %s" % table
        else:
            return 'error'
        cursor = self.conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        return result

    def update(self, sql):
        if not self.conn: return
        if sql:
            cursor = self.conn.cursor()
            cursor.execute(sql)
            self.conn.commit()
            cursor.close()
            return 'success'
        else:
            return 'error'

    def statement(self):
        statement = f'{self.__class__.__name__}\n' \
                         '作者: 梦辰雪（Cui Mengchao）\n' \
                         '版本号: v1.0.0\n' \
                         '更新时间: 2023-05-10\n' \
                         'gitee: https://gitee.com/mcxgitee\n'
        print(f'\033[1;33m{statement}\033[0m\n')

# region 单例
instance = None

def initInstance(statement=True):
    global instance
    if not instance:
        instance = MysqlUtilsWithUI(statement=statement)
    return instance
# endregion